package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @program: gulimall
 * @description:
 * @author: 江天赐
 * @create: 2022-08-04 22:51
 */
@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redisson;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {
        //TODO:1.查出所有的1级分类
        List<CategoryEntity> entities = categoryService.getLevel1Categorys();
        //默认前缀  classpath:/templates/
        //默认后缀 .html
        //视图解析器进行拼串  classpath:/templates/+"返回值"(index)+.html
        model.addAttribute("categorys", entities);
        return "index";
    }

    // index/json/catalog.json
    @ResponseBody
    @GetMapping("/index/json/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        Map<String, List<Catelog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String sayHello() {
        //1.获取一把锁，只要锁的名字一样，就是同一把锁
        RLock lock = redisson.getLock("my-lock");

        //2.加锁
        lock.lock();//阻塞式等待，默认加的锁过期时间为30s
        //1.锁的自动续期，如果业务超长，运行期间自动给锁续上新的30s，不用担心业务时间过长，锁自动过期被删掉
        //2.加锁的业务只要运行完成，就不会给当前锁续期，即使不手动解锁，锁在30s后也会自动删除
        //3.

//        lock.lock(10, TimeUnit.SECONDS);//10s自动解锁  自动解锁时间一定要大于业务时间
        //问题：lock.lock(10, TimeUnit.SECONDS); 锁到期了，不会自动续期
        //1.如果我们传递了锁的超时时间，就发送给redis执行lua脚本，进行占锁，默认超时时间就是我们指定的时间10s
        //2.如果我们未指定锁的超时时间，就使用30*1000【lockWatchdogTimeout 看门狗默认时间】
        //只要占锁成功，就会启动一个定时任务【重新给锁设置过期时间，新的过期时间就是看门狗默认时间】
        // internalLockLeaseTime【看门狗时间】 / 3L，10s

        //最佳实战
        //lock.lock(10, TimeUnit.SECONDS);省掉了续期操作
        try {
            System.out.println("加锁成功，执行业务。。。" + Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //3.解锁
            System.out.println("释放锁。。。" + Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }

    //保证一定能读到最新数据，修改期间，写锁是一个排它锁(互斥锁、独享锁),读锁是一个共享锁
    //读+读，相当于无锁，并发读，只会在redis中记录好，所有当前的读锁，他们都会同时加锁成功。
    //写锁没释放读就必须等待
    //写+读，等待写锁释放
    //写+写，阻塞方式
    //读+写，有读锁，写也需要等待
    //只要有写的存在，都必须等待
    @GetMapping("/write")
    @ResponseBody
    public String writeValue() {
        RReadWriteLock readWriteLock = redisson.getReadWriteLock("rw-lock");

        String s = "";
        RLock wLock = readWriteLock.writeLock();
        try {
            wLock.lock();
            //1.改数据加写锁，读数据加读锁
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            stringRedisTemplate.opsForValue().set("writeValue", s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            wLock.unlock();
        }
        return s;
    }

    @GetMapping("/read")
    @ResponseBody
    public String readValue() {
        RReadWriteLock readWriteLock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = readWriteLock.readLock();
        String s = "";
        try {
            rLock.lock();
            s = UUID.randomUUID().toString();
            String writeValue = stringRedisTemplate.opsForValue().get("writeValue");
        } finally {
            rLock.unlock();
        }
        return s;
    }

    /**
     * 车库停车
     * 3车位
     * 信号量可以用来做分布式限流
     */
    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
        park.acquire();//获取一个信号，获取一个值，阻塞式
//        park.tryAcquire() //非阻塞式
        return "ok";
    }

    @GetMapping("/go")
    @ResponseBody
    public String go() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
        park.release();//释放一个信号，释放一个车位
        return "ok";
    }

    /**
     * 放假，锁门
     * 1班没人了
     * 5个班全部走完，锁大门
     */
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.await();//等待闭锁(CountDownLatch)都完成
        return "放假了...";
    }

    @GetMapping("/gogogo/{id}")
    @ResponseBody
    public String gogogo(@PathVariable Long id) {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown();//计数-1
        return id + "班的人都走了...";
    }
}
